package org.hazelnuts;

import org.hazelnuts.dao.UserRepository;
import org.hazelnuts.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dao.DuplicateKeyException;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SpringBootApplication
public class OracleCommandApplication implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(OracleCommandApplication.class);

    @Autowired
    private UserRepository userRepository;

    public static void main(String args[]) {
        SpringApplication.run(OracleCommandApplication.class, args);
    }

    public void saveToOracle(String filePath, String tableName) throws IOException {
        //建立缓冲文本输入流
        int bufferSize = 20 * 1024 * 1024;//设读取文件的缓存为20MB
        File file = new File(filePath);
        if (!file.exists()) {
            logger.warn("文件不存在，请检查文件路径是否正确！");
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream);
        BufferedReader inputReader = new BufferedReader(inputStreamReader, bufferSize);

        BufferedReader[] inputStreams = new BufferedReader[2];
        int alternate = 0;
        int counter = 0;
        inputStreams[0] = inputReader;
        while (inputStreams[alternate % 2] != null) {
            counter = SaveModelToRepository(inputStreams[alternate % 2], counter, alternate, tableName);
            inputStreams[alternate % 2] = null;

            alternate++;
            if (fileInputStream.getFD().valid()) {
                inputStreams[alternate % 2] = inputReader;
            } else {
                inputReader.close();
            }
        }
        logger.info("数据导入完成，共导入：" + counter + "，共跳过：" + alternate);
    }

    protected int SaveModelToRepository(BufferedReader input, int counter, int alternate, String tableName) throws IOException {
        int rowNumber = counter + alternate;
        // 创建 Pattern 对象
        //Pattern pattern = Pattern.compile("(\\d+)(,)(\\d)(,)(.*)");
        Pattern pattern = Pattern.compile("(\\d+)(,)(.*)");
        String line = null;
        //逐行读取，逐行输出
        try {
            while ((line = input.readLine()) != null) {
                rowNumber++;

                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    Long id = Long.parseLong(matcher.group(1));
                    //Integer age = Integer.parseInt(matcher.group(3));
                    String name = matcher.group(3);
                    if (name.length() > 4000) {
                        name = name.substring(0, 3999);
                    }
                    userRepository.insert(new User(id, name, 0), tableName);
                    counter++;
                } else {
                    logger.info("数据格式错误,位置在： " + rowNumber + "，源数据： " + line);
                }
            }
        } catch (DuplicateKeyException ex) {
            logger.error("数据重复写入,位置在： " + rowNumber + "，源数据： " + line);
            return counter;
        } catch (Exception ex) {
            logger.error("数据写入异常,位置在： " + rowNumber + "，源数据： " + line);
            logger.error(ex.getMessage(), ex);
            return counter;
        }

        input.close();
        return counter;
    }

    @Override
    public void run(String... args) throws Exception {
        long startTime = System.currentTimeMillis();

//        if (null != args) {
//            if (args.length == 4) {
//                if (args[0].equals("--path") && args[2].equals("--table")) {
//                    logger.info("开始导入文件数据：" + args[1].trim());
//                    saveToOracle(args[1].trim(), args[3].trim());
//                }
//            } else {
//                logger.warn("程序参数格式错误，请重新运行程序！");
//            }
//        }

        DataExportTest dataExportTest = new DataExportTest();
        dataExportTest.exportTest();

//        for (int i = 0; i < 100000; i++) {
//            userRepository.testSql();
//        }

        long stopTime = System.currentTimeMillis();
        logger.info("程序运行时间： " + (stopTime - startTime) + "(ms)");
    }
}